﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using QD.Utill;
using QD.Snapshot.Core.Config;
using NSoup.Nodes;
using NSoup.Select;
using System.Net;
using QD.Snapshot.Core.Util;

namespace QD.Snapshot.Core.BLL
{
   public class Search_GuoSou : SearchBase
    {
       static string uid = "CgqASVo8ahksrQQiD6ZvAg==";
        public Search_GuoSou(TextBox textBox, int SleepTime)
        {
            this.textBox = textBox;
            this.SleepTime = SleepTime;
            this.copyform = "4";        //Bing搜索
            Echo("国搜截图已启动");
        }


        Regex r = new Regex("href='([\\s\\S].*?)'");
        static Model.TaskModel_360 taskModel = new Model.TaskModel_360();
        static HttpRequest Http = new HttpRequest("Mozilla/5.0 (compatible;Windows NT 6.1; WOW64;Trident/6.0;MSIE 9.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.27 Safari/537.36",
                 "http://www.chinaso.com/search/pagesearch.htm");
        public override void Search(string keyword, Model.Product product, Model.WebSite company)
        {
            string html = string.Empty;
            string msg = string.Empty;
            Thread.Sleep(SleepTime);
            Http.ClearCookie();
            Http.AddCookie("uid", uid, "chinaso.com", DateTime.Now.AddYears(1));

            //Http.SetProxy("111.13.7.122", 80);

            msg = Http.Requset(string.Format(Engine.URL_GuoSou, keyword), out html);

            IsCode_GuoSou = CheckValidate(html);   //是否出现验证码

            if (msg.Length > 0)
            {
                Echo(string.Format("搜索 {0} 返回错误", keyword));
            }
            else if (IsCode_GuoSou)
            {
                EchoLog("code", "国搜 出现验证码");
                Thread.Sleep(1000);
                if (r.IsMatch(html))
                    SendHtml(r.Match(html).Groups[1].Value);
                else
                {
                    string tempstr = string.Empty;
                    Random random = new Random();
                    for (int i = 0; i < 5; i++)
                        tempstr += (char)random.Next((int)'a', (int)'z');
                    SendHtml("http://www.chinaso.com/search/ipaccess/verifyres/?&str=" + tempstr);
                }
            }
            else
            {
                Echo(string.Format("搜索 {0}", keyword));

                taskModel.itemid = product.itemid;
                taskModel.keyword = keyword;
                taskModel.company = company;
                taskModel.html = html;

                NumHelper.Instance.SetNumGuoSou(1);    //统计搜索速度

                //CheckOrAdd(taskModel.html, taskModel.keyword, taskModel.itemid, taskModel.company);

                ThreadPool.QueueUserWorkItem(new WaitCallback(CheckOrAdd), taskModel);
            }

        }

        void CheckOrAdd(object obj)
        {
            Model.TaskModel_360 model = obj as Model.TaskModel_360;

            CheckOrAdd(model.html, model.keyword, model.itemid, model.company);

            model = null;
        }

        void CheckOrAdd(string html, string keyword, int itemid, Model.WebSite company)
        {
            //html = Regex.Replace(html, "<!--([\\s\\S].*?)-->", "");

            NSoup.Nodes.Document doc = NSoup.NSoupClient.Parse(html);
            Regex r1 = new Regex(FixRegex(company.ShortName), RegexOptions.IgnoreCase);
            Regex r2 = new Regex(FixRegex(keyword), RegexOptions.IgnoreCase);
            Regex SiteName = new Regex(FixRegex(company.SiteName), RegexOptions.IgnoreCase);
            Regex Cellphone = new Regex(FixRegex(company.Cellphone), RegexOptions.IgnoreCase);
            Regex phone = new Regex(FixRegex(company.Phone), RegexOptions.IgnoreCase);

            CheckOrAdd(doc, r1, SiteName, Cellphone, phone, itemid, company.UserID, keyword);
        }

        void CheckOrAdd(Document doc, Regex r1, Regex SiteName, Regex Cellphone, Regex phone, int itemid, int userid, string keyword, int page = 1)
        {

            Elements result = doc.GetElementsByClass("reItem");
            if (result == null) return;

            HideElement(doc.GetElementById("boxImageleftA"));               //隐藏 国搜图片
            HideElement(doc.GetElementById("lunabox_video"));               //隐藏 国搜视频
            HideElementList(doc.GetElementsByClass("reBox"));               //隐藏 左侧电影、招聘、购物
            HideElementList(doc.GetElementsByClass("reNewsImgWrapper"));    //隐藏 每行左侧图片
            //HideElementList(doc.GetElementsByClass("relatedWrapper"));      //隐藏 右侧


            int index = 0;
            bool isFirst = true;
            string nums_html = "";

            foreach (Element ele in result)
            {
                index++;

                if (r1.IsMatch(ele.Text()) || CheckShortNameList(ele.Text()) || CheckQJY(ele.Text(), SiteName, Cellphone, phone))
                {
                    //SetUrlName(ele.Text());  //记录上词平台

                    //AddSnap(doc.Html(), GetMd5(ele.GetElementsByTag("h2").Text));

                    string index_key = GetMd5(ele.GetElementsByTag("h2").Text); //第几行的key,更新时，用来确定更新哪一行
                    string platform = GetPlatform(ele.Text());                  //上词的平台

                    if (string.IsNullOrEmpty(platform))
                    {
                        //platform = ele.Select(".snapshot").Text;         //找不到平台,用域名代替
                        //if (platform.Contains("&nbsp"))
                        //    platform = platform.Substring(0, platform.IndexOf("&nbsp"));
                        platform = "0";//找不到平台，给予0表示
                    }

                    if (isFirst)
                    {
                        Elements item = doc.GetElementsByClass("reNewsContL");
                        if (item != null)
                            item.RemoveClass("fr"); //内容100%填充

                        RemoveAttr(result);
                        nums_html = "<span id='sp_nums' class='sp_nums' data='" + doc.Select(".pageTotal").Text + "'></span>";
                        isFirst = false;
                    }

                    //添加成功记录
                    AddSnap(page, userid, itemid, index, keyword, result.OuterHtml() + nums_html, platform, index_key);
                }
            }
        }

        protected override void RemoveAttr(Elements result)
        {
            Elements ele = result.Select("a");
            ele.Attr("href", "#");
            ele.RemoveAttr("target");

            Elements script = result.Select("script");
            script.Remove();
        }

       //中国搜索的验证提示
        bool CheckValidate(string html) {
            Regex r = new Regex("ADDRESS|验证码");
            return r.IsMatch(html);
        }

        static CookieContainer cc = new CookieContainer();
       /// <summary>
       /// 激活中国搜索
       /// </summary>
       /// <param name="url"></param>
        public void SendHtml(string url) {
            HttpWebRequest request = null;
            try
            {
                cc.Add(new System.Net.Cookie("uid", uid, "/", "chinaso.com"));
                request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.UserAgent = "Mozilla/5.0 (compatible;Windows NT 6.1; WOW64;Trident/6.0;MSIE 9.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.27 Safari/537.36";
                request.CookieContainer = cc;
                request.Referer = "http://www.chinaso.com/search/pagesearch.htm";
                WebResponse response = null;
                try
                {
                    response = request.GetResponse();
                }
                catch (WebException ex) {
                    response = ex.Response;
                }
                response.Close();
            }
            catch{ return;}
            finally
            {
                if (request != null)
                    request.Abort();
                GC.Collect();
            }
        }
    }
}